package com.turing.manage.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @desc   url控制器
 * @author fx
 * @time   2021-12-14
 */
public class SessionFilter implements Filter{
	
	
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("SessionFilter过滤器初始化");
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		
		System.out.println("SessionFilter开始过滤");
		
		//0.通过强转获取request和response对象
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		//1.获取用户访问的页面
		String path = request.getServletPath();
		System.out.println("path-->"+path);
		
		//2.如果是特权页面，需要放行
		if (("/manage/login.jsp".equals(path))||("/manage/login.do".equals(path)))
		{
			System.out.println("当前:"+path+":是特权页面，所以直接放行");
			chain.doFilter(request, response);
			return;
		}
		
		
		//3.没有登录是不能放行的(检查一下session作用域中是否有值，有值既可放行，没有则不能访问)
		HttpSession session = request.getSession();
		if (session.getAttribute("user")==null) 
		{
			System.out.println("当前用户没有登录，不能访问");
			String errorMessage = "请先登录，不能非法访问";
			request.setAttribute("errorMsg", errorMessage);
			request.getRequestDispatcher("/manage/error.jsp").forward(request, response);
			return;
		}
		else
		{
			System.out.println("过滤通过(session中有值，那就是用户已经登录了),放行");
			chain.doFilter(request, response);
			return;
		}
	}

	public void destroy() {
		System.out.println("SessionFilter销毁");
	}
	
	
}
